import 'dart:math';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_massage/common_lib/http/common_net.dart';
import 'package:flutter_massage/common_lib/index.dart';
import 'package:flutter_massage/common_lib/routers/route.dart';
import 'package:flutter_massage/service/index.dart';
import 'package:flutter_massage/values/index.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:shanyan/shanYanResult.dart';
import 'package:shanyan/shanYanUIConfig.dart';
import 'package:shanyan/shanyan.dart';

class ApiLogin extends CommonApi {
  ApiLogin._(Map<String, dynamic> params) : super('sign/?a=index', params);

  ApiLogin.sendCode(String mobile) : this._({'mobile': mobile, 'signature': XydUserService.instance.signature});

  ApiLogin.login(String mobile, String code)
      : this._({'mobile': mobile, 'signature': XydUserService.instance.signature, 'code': code});

  ApiLogin.logout() : this._({});

  ApiLogin.cancellation() : this._({'cancel_member': '1'});

  ApiLogin.quickLogin(Map<String, dynamic> result)
      : this._({'signature': XydUserService.instance.signature, 'result': result});
}

class LoginLogic extends GetxController {
  final TextEditingController phoneController = TextEditingController();
  final TextEditingController codeController = TextEditingController();
  final FocusNode phoneNode = FocusNode();
  final FocusNode codeNode = FocusNode();

  var agreeProtocol = false.obs;
  var showPhoneError = false.obs;
  var showCodeError = false.obs;

  String quickLoginPhone = '';

  OneKeyLoginManager oneKeyLoginManager = OneKeyLoginManager();

  @override
  void onReady() async {
    super.onReady();

    callQuickLogin();
  }

  void callQuickLogin() async {
    ///配置UI
    configUI(oneKeyLoginManager.shanYanUIConfig);

    ///初始化  测试：1ZQDejuO  正式：9CQFnvJn
    await oneKeyLoginManager.init(appId: '9CQFnvJn');

    ///预取号
    await oneKeyLoginManager.getPhoneInfo();

    ///一键登录事件监听
    oneKeyLoginManager.setOneKeyLoginListener((ShanYanResult shanYanResult) {
      if (1000 == shanYanResult.code) {
        ///一键登录获取token成功
        quickLogin(shanYanResult.token ?? '');
      } else if (1011 == shanYanResult.code) {
        ///点击返回/取消 （强制自动销毁）
      } else {
        ///一键登录获取token失败
        //关闭授权页
        oneKeyLoginManager.finishAuthControllerCompletion();
      }
    });

    ///调起授权页
    oneKeyLoginManager.openLoginAuth().then((ShanYanResult shanYanResult) async {
      if (1000 == shanYanResult.code) {
        ///拉起授权页成功
        print('拉起授权页成功');
      } else {
        ///拉起授权页失败
        print('拉起授权页失败');
      }
    });
  }

  Future quickLogin(String token) async {
    if (Loading.predicate(() => token.empty, '未获取到token')) return;
    dynamic json = await CommonNet.post(ApiLogin.quickLogin({'token': token}));
    if (json['code'] == 200) {
      openMain(key: json['data']['key']);
    } else {
      String? message = json['response'];
      Loading.toast(message ?? '一键登录失败，请使用验证码登录');
    }
  }

  void configUI(ShanYanUIConfig shanYanUIConfig) {
    shanYanUIConfig.ios.isFinish = false;

    // shanYanUIConfig.ios.setPreferredStatusBarStyle = iOSStatusBarStyle.styleLightContent;
    shanYanUIConfig.ios.setStatusBarHidden = false;
    shanYanUIConfig.ios.setAuthNavHidden = false;
    shanYanUIConfig.ios.setNavigationBarStyle = iOSBarStyle.styleBlack;
    shanYanUIConfig.ios.setAuthNavTransparent = true;

    shanYanUIConfig.ios.setNavReturnImgHidden = false;

    shanYanUIConfig.ios.setNavigationBottomLineHidden = false;

    shanYanUIConfig.ios.setLogoImgPath = 'test';
    shanYanUIConfig.ios.setLogoCornerRadius = 50;
    shanYanUIConfig.ios.setLogoHidden = false;

    shanYanUIConfig.ios.setNumberColor = "#333333";
    shanYanUIConfig.ios.setNumberSize = 22;
    shanYanUIConfig.ios.setNumberBold = true;
    shanYanUIConfig.ios.setNumberTextAlignment = iOSTextAlignment.center;

    shanYanUIConfig.ios.setLogBtnText = "本机号码一键登录";
    shanYanUIConfig.ios.setLogBtnTextColor = "#FFFFFF";
    shanYanUIConfig.ios.setLoginBtnTextSize = 16;
    shanYanUIConfig.ios.setLoginBtnTextBold = false;
    shanYanUIConfig.ios.setLoginBtnBgColor = "#31C3A3";
    shanYanUIConfig.ios.setLoginBtnCornerRadius = 22;

    shanYanUIConfig.ios.setPrivacyTextSize = 12;
    shanYanUIConfig.ios.setPrivacyTextBold = false;

    shanYanUIConfig.ios.setAppPrivacyTextAlignment = iOSTextAlignment.center;
    shanYanUIConfig.ios.setPrivacySmhHidden = true;
    shanYanUIConfig.ios.setAppPrivacyLineSpacing = 5;
    shanYanUIConfig.ios.setAppPrivacyNeedSizeToFit = false;
    shanYanUIConfig.ios.setAppPrivacyColor = ["#333333", "#31C3A3"];

    shanYanUIConfig.ios.setAppPrivacyNormalDesTextFirst = "同意并接受";
    shanYanUIConfig.ios.setAppPrivacyNormalDesTextSecond = "和";
    shanYanUIConfig.ios.setAppPrivacyFirst = ["《用户协议》", "https://lami.chwxkj.top/sites/service-agreement.html"];
    shanYanUIConfig.ios.setAppPrivacyNormalDesTextThird = "和";
    shanYanUIConfig.ios.setAppPrivacySecond = ["《隐私政策》", "https://lami.chwxkj.top/sites/privacy.html"];
    shanYanUIConfig.ios.setAppPrivacyNormalDesTextFourth = "。";

    shanYanUIConfig.ios.setAppPrivacyWebPreferredStatusBarStyle = iOSStatusBarStyle.styleDefault;
    shanYanUIConfig.ios.setAppPrivacyWebNavigationBarStyle = iOSBarStyle.styleDefault;

    //运营商品牌标签("中国**提供认证服务")，不得隐藏
    shanYanUIConfig.ios.setSloganTextSize = 11;
    shanYanUIConfig.ios.setSloganTextBold = false;
    shanYanUIConfig.ios.setSloganTextColor = "#333333";
    shanYanUIConfig.ios.setSloganTextAlignment = iOSTextAlignment.center;

    shanYanUIConfig.ios.setCheckBoxHidden = false;
    shanYanUIConfig.ios.setPrivacyState = false;
    shanYanUIConfig.ios.setCheckBoxVerticalAlignmentToAppPrivacyTop = true;
    shanYanUIConfig.ios.setUncheckedImgPath = "check_normal";
    shanYanUIConfig.ios.setCheckedImgPath = "check_selected";
    shanYanUIConfig.ios.setCheckBoxWH = [14, 14];
    // shanYanUIConfig.ios.setCheckBoxImageEdgeInsets = [6, 12, 6, 0];

    shanYanUIConfig.ios.setLoadingCornerRadius = 10;
    shanYanUIConfig.ios.setLoadingBackgroundColor = "#E68147";
    shanYanUIConfig.ios.setLoadingTintColor = "#1C7EFF";

    shanYanUIConfig.ios.setShouldAutorotate = false;
    shanYanUIConfig.ios.supportedInterfaceOrientations = iOSInterfaceOrientationMask.all;
    shanYanUIConfig.ios.preferredInterfaceOrientationForPresentation = iOSInterfaceOrientation.portrait;

    shanYanUIConfig.ios.setAuthTypeUseWindow = true;
    shanYanUIConfig.ios.setAuthWindowCornerRadius = 10;

    shanYanUIConfig.ios.setAuthWindowModalTransitionStyle = iOSModalTransitionStyle.flipHorizontal;
    shanYanUIConfig.ios.setAppPrivacyWebModalPresentationStyle = iOSModalPresentationStyle.fullScreen;
    shanYanUIConfig.ios.setAuthWindowOverrideUserInterfaceStyle = iOSUserInterfaceStyle.unspecified;

    shanYanUIConfig.ios.setAuthWindowPresentingAnimate = true;

    //弹窗中心位置
    shanYanUIConfig.ios.layOutPortrait.setAuthWindowOrientationCenterX = ScreenUtil().screenWidth * 0.5;
    shanYanUIConfig.ios.layOutPortrait.setAuthWindowOrientationCenterY = ScreenUtil().screenHeight * 0.5;

    shanYanUIConfig.ios.layOutPortrait.setAuthWindowOrientationWidth = ScreenUtil().screenWidth;
    shanYanUIConfig.ios.layOutPortrait.setAuthWindowOrientationHeight = ScreenUtil().screenHeight;

    //logo
    shanYanUIConfig.ios.layOutPortrait.setLogoTop = 52 + ScreenUtil().statusBarHeight + kToolbarHeight;
    shanYanUIConfig.ios.layOutPortrait.setLogoWidth = 100;
    shanYanUIConfig.ios.layOutPortrait.setLogoHeight = 100;
    shanYanUIConfig.ios.layOutPortrait.setLogoCenterX = 0;

    //手机号控件
    shanYanUIConfig.ios.layOutPortrait.setNumFieldTop = (shanYanUIConfig.ios.layOutPortrait.setLogoTop ?? 0) +
        (shanYanUIConfig.ios.layOutPortrait.setLogoHeight ?? 0) +
        40;
    shanYanUIConfig.ios.layOutPortrait.setNumFieldCenterX = 0;
    shanYanUIConfig.ios.layOutPortrait.setNumFieldHeight = 30;
    shanYanUIConfig.ios.layOutPortrait.setNumFieldWidth = 150;

    //一键登录按钮
    shanYanUIConfig.ios.layOutPortrait.setLogBtnTop = (shanYanUIConfig.ios.layOutPortrait.setNumFieldTop ?? 0) +
        (shanYanUIConfig.ios.layOutPortrait.setNumFieldHeight ?? 0) +
        40;
    shanYanUIConfig.ios.layOutPortrait.setLogBtnCenterX = 0;
    shanYanUIConfig.ios.layOutPortrait.setLogBtnHeight = 44;
    shanYanUIConfig.ios.layOutPortrait.setLogBtnWidth = 310;

    //授权页 slogan（***提供认证服务）
    shanYanUIConfig.ios.layOutPortrait.setSloganHeight = 15;
    shanYanUIConfig.ios.layOutPortrait.setSloganLeft = 0;
    shanYanUIConfig.ios.layOutPortrait.setSloganRight = 0;
    shanYanUIConfig.ios.layOutPortrait.setSloganBottom = 25;

    //隐私协议
    shanYanUIConfig.ios.layOutPortrait.setPrivacyLeft = 30;
    shanYanUIConfig.ios.layOutPortrait.setPrivacyRight = 30;
    shanYanUIConfig.ios.layOutPortrait.setPrivacyBottom = 50;
  }

  /// 切换协议状态
  void clickAgreeProtocol() => agreeProtocol.value = !agreeProtocol.value;

  /// 手机号验证
  bool get isNotPhone => phoneController.value.text.length != 11;

  /// 验证码长度验证
  bool get isVerificationCodeRight => codeController.text.notEmpty;

  /// 验证码验证
  bool get isNotCode => !isVerificationCodeRight;

  /// 发送验证码
  Future<bool> sendCode() async {
    showPhoneError.value = isNotPhone;
    if (isNotPhone) return Future.value(false);

    Loading.show();

    try {
      await CommonNet.post(ApiLogin.sendCode(phoneController.value.text));
      Loading.toast("验证码已发送!", dismissLoading: true);
      return true;
    } catch (e) {
      Loading.dismiss();
    }
    return false;
  }

  /// 收起键盘
  void hideKeyboard() => CommonOperate.hideKeyboard();

  /// 登录
  Future login() async {
    showPhoneError.value = isNotPhone;
    if (isNotPhone) {
      phoneNode.requestFocus();
      return;
    }

    showCodeError.value = isNotCode;
    if (isNotCode) {
      codeNode.requestFocus();
      return;
    }

    if (!agreeProtocol.value) {
      hideKeyboard();
      CommonDialog.twoButton(
        descriptionWidget: Text.rich(
          TextSpan(
            text: '需要同意',
            children: [
              TextSpan(
                text: '《使用协议》、',
                style: const TextStyle(color: AppColors.primaryGreen),
                recognizer: TapGestureRecognizer()..onTap = CommonRoute.openProtocolPage,
              ),
              TextSpan(
                text: '《隐私政策》',
                style: const TextStyle(color: AppColors.primaryGreen),
                recognizer: TapGestureRecognizer()..onTap = CommonRoute.openPrivacyPage,
              ),
              const TextSpan(text: '才能登录'),
            ],
          ),
          style: const TextStyle(color: AppColors.textLevelOne, fontSize: 15, height: 1.5),
        ),
        confirmTitle: '同意',
        onConfirm: () async {
          agreeProtocol.value = true;
          await callLoginApi();
        },
      );
      return;
    }
    await callLoginApi();
  }

  Future callLoginApi() async {
    hideKeyboard();

    Loading.show();
    String phoneNum = phoneController.text;
    String code = codeController.text;
    dynamic json = await CommonNet.post(ApiLogin.login(phoneNum, code));
    if (json['code'] == 200) {
      Loading.dismiss();
      openMain(key: json['data']['key']);
    } else {
      String? message = json['response'];
      Loading.toast(message ?? '登录失败');
    }
  }

  Future openMain({required String key}) async {
    Storage().setString(StorageKey.userKey, key);

    ///生成一个随机昵称
    String nickName = Storage().getString('${StorageKey.nameKey}-$key', defaultValue: '');
    if (nickName.empty) {
      var random = Random();
      var randomNumber = random.nextInt(90000) + 10000;
      nickName = '用户$randomNumber';
      await Storage().setString('${StorageKey.nameKey}-$key', nickName);
    }

    CommonRoute.openMain();
  }
}
